import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder} from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';

import {NzMessageService} from 'ng-zorro-antd/message';
import {GoodsAllService} from './goods-all.service';
import {PermissionService} from '../../../service/permission.service';

@Component({
  selector: 'app-goods-all',
  templateUrl: './goods-all.component.html',
  styleUrls: ['./goods-all.component.scss'],
})
export class GoodsAllComponent implements OnInit {

  isVisible = false;

  validateForm!: any;
  // // 查询表格初始化
  // queryForm!: any;


  listOfData?: any;

  checked = false;
  /**
   * 列表查询条件
   */
  queryForm: any = {
    // 商品编号或名称
    name: '',
    // 商品类型id
    typeId: '',
    // 商品品牌ids
    brandIds: '',
    // 状态 -1 全部  0无效 1 有效 2下架
    status: '-1',
    // 创建日期-起始时间
    createTimeStart: '',
    // 创建日期-结束时间
    createTimeEnd: '',
    // 时间区间(控件使用)
    nzFormat: '',
    // 当前页码
    current: '1',
    // 分页大小
    size: '20',
    // 排序字段：0-默认方式，1-b端价格、2-c端价格、3-销量、4-销售库存、5-冻结库存、6-类型
    orderField: 0,
    // 排序方式：true-升序排序、false-降序排序
    asc: false,
    // 货主
    supplierIds: ''
  };
  /**
   * 当前是否在搜索
   */
  searchHint = false;
  /**
   * 表格是否加载中
   */
  tableLoading: any = false;
  /**
   * 当前搜索name
   */
  searcName = '';
  /**
   * 全局 loading
   */
  messageId: any = null;
  /**
   * 类型下拉
   */
  GoodsTypeList: any = [];
  /**
   * 加载失败显示图像占位符
   */
  fallback =
    '';

  /**
   * 路由缓存恢复时
   */
  static updateCache: any = null;
  cacheData: any = {
    goodsTypeIdList: [],
    brandList: [] // 商品品牌list
  };
  // 商品品牌selected
  brandArrys: any = [];
  // 货主下拉
  cargoOwnerOptions: any = [];
  cargoOwnerSlected: any = [];
  isSelectLoading: boolean = false;
  cargoOwnerForms: any = {
    page: 1,
    pageSize: 20,
    total: 0
  }

  /**************************************** 水印 START ****************************************/
  modelType: number = 0; // 0：添加，1：去除
  isModelVisible: boolean = false;
  modalTitle: string = '提示';
  isConfirmLoading: boolean = false;
  uploadImgLoading: boolean = false;
  identityOptions: any = [
    { label: 'B端', value: '0', checked: false },
    { label: 'C端', value: '1', checked: false }
  ];
  positionOptions: any = [
    { label: '左上', value: 'nw' },
    { label: '中上', value: 'north' },
    { label: '右上', value: 'ne' },
    { label: '左中', value: 'west' },
    { label: '中部', value: 'center' },
    { label: '右中', value: 'east' },
    { label: '左下', value: 'sw' },
    { label: '中下', value: 'south' },
    { label: '右下', value: 'se' }
  ];
  modelForemParams: any = {
    imgList: [],
    file: null,
    imgUrl: '',
    type: '',
    position: ''
  };
  checkedIds: any = [];
  /**************************************** 水印 END ****************************************/

  constructor(
    private router: Router,
    private GoodsAllService: GoodsAllService,
    private fb: FormBuilder,
    private message: NzMessageService,
    public permission: PermissionService,
    private modal: NzModalService
  ) {
    this.modelForemParams.file = null;
    this.modelForemParams.imgUrl = '';
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      formLayout: ['horizontal'],
    });

    GoodsAllComponent.updateCache = () => {
      this.tableLoading = false;
      this.getList();
    };
    this.getList();
    this.getGoodsTypeList();

    // 获取商品品牌list
    this.getBrandListData();
    // 获取货主list
    this.querySupplierList();
  }

  /**
   * 查询
   */
  query(): void {
    this.queryForm.orderField = 0;
    this.queryForm.asc = false;
    this.getList();
  }
  /**
   * 重置
   */
  resetData() {
    this.queryForm.name = '';
    this.queryForm.typeId = '';
    this.queryForm.brandIds = '';
    this.queryForm.status = '-1';
    this.queryForm.createTimeStart = '';
    this.queryForm.createTimeEnd = '';
    this.queryForm.nzFormat = '';
    this.queryForm.supplierIds = '';
    this.queryForm.goodsTypeId = '';

    this.cacheData.goodsTypeIdList = [];
    this.cargoOwnerSlected = [];
    this.brandArrys = [];

    this.queryForm.current = 1;
    this.getList();
  }

  /**
   * 分类下拉
   */
  getGoodsTypeList() {
    this.GoodsAllService.getGoodsTypeList().subscribe((res: any) => {
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.GoodsTypeList = this.addFieldArr(res.data);
    }, err => {
    });
  }

  /**
   * 跳转详情页
   * @param id
   */
  toEdit(id: any = 0) {
    this.router.navigate(['goods/goodsTabs', id]);
  }

  /**
   * 搜索返回原列表
   */
  backList() {
    this.queryForm.name = '';
    this.queryForm.current = 1;
    this.queryForm.nzFormat = '';
    this.queryForm.status = '-1';
    this.queryForm.typeId = '';
    this.queryForm.brandIds = '';
    this.searchHint = false;
    this.checked = false;
    this.getList();
  }

  /**
   * item单选
   * @param id
   * @param checked
   */
  onItemChecked(id: number, checked: boolean): void {
    console.log('id:' + id + ',checked:' + checked);
    const index = this.listOfData.records.findIndex((item: { id: number; }) => item.id === id);
    this.listOfData.records[index].Checked = checked;
    this.updataCheckAll();
  }

  /**
   * 全选
   * @param value
   */
  onAllChecked(value: boolean): void {
    this.listOfData.records.forEach((item: { Checked: boolean; }) => item.Checked = value);
    console.log(value);
  }

  /**
   * 判断item是否全部选择
   */
  updataCheckAll() {
    const index = this.listOfData.records.findIndex((item: { Checked: boolean; }) => item.Checked == false);
    console.log(index);

    if (index != -1) {
      this.checked = false;
    } else {
      this.checked = true;
    }
  }

  /**
   * 全部删除
   */
  onAllDel() {
    var outMealServicelist = this.listOfData.records.filter(function(item: { Checked: boolean; }) {
      return item.Checked == true;
    });
    for (let index = 0; index < outMealServicelist.length; index++) {
      const element = outMealServicelist[index];
    }
  }

  //  orderField 排序字段：0-默认方式，1-b端价格、2-c端价格、3-销量、4-销售库存、5-冻结库存、6-类型
  // asc true-升序排序、false-降序排序
  onTableFilter(val: any) {
    this.queryForm.orderField = val;
    this.queryForm.asc = !this.queryForm.asc;
    this.getList();
  }

  /**
   * 页码改变
   * @param index
   */
  onPageIndexChange(index: number) {
    // console.log(index);
    this.queryForm.current = index;
    this.checked = false;
    this.getList();
  }

  /**
   * 每页条数改变的回调
   * @param index
   */
  onPageSizeChange(index: number) {
    // console.log(index);
    this.queryForm.size = index;
    this.getList();
  }

  /**
   * 删除
   * @param item
   */
  confirm(item: any) {
    if (item.skuGroupName) {
      return this.createMessage('warning', '该商品已经关联规格组，请解绑后重试');
    }
    if (this.messageId != null) {
      return;
    }
    this.createBasicMessage();
    this.GoodsAllService.delete(item.id).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', '删除成功');
      this.getList();
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 复制商品
   */
  copyGoods(id: any) {
    if (this.messageId != null) {
      return;
    }
    this.createBasicMessage();
    this.GoodsAllService.copy(id).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', '复制成功');
      this.getList();
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 刷新列表
   */
  refresh() {
    this.listOfData = [];
    this.getList();
  }

  /**
   * 查询列表
   * @returns
   */
  getList() {
    if (this.tableLoading) {
      return;
    }
    this.listOfData = [];
    this.tableLoading = true;

    this.checked = false;
    this.GoodsAllService.get(this.queryForm).subscribe((res: any) => {
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }

      res.data.records.forEach((element: any) => {
        element['Checked'] = false;
      });
      let textArr = [];
      if (this.queryForm.name) {
        textArr.push(this.queryForm.name);
      }
      if (this.queryForm.typeId) {
        textArr.push(this.queryForm.typeId);
      }
      if (this.queryForm.brandIds) {
        textArr.push(this.queryForm.brandIds);
      }
      if (this.queryForm.status) {
        textArr.push(this.queryForm.status);
      }
      if (this.queryForm.nzFormat) {
        textArr.push(this.queryForm.nzFormat);
      }
      this.searcName = textArr.join(' | ');

      this.listOfData = res.data;
      this.tableLoading = false;
    }, err => {
      this.tableLoading = false;
      this.createMessage('error', err.message);
    });
  }

  /**
   * 批量下架
   */
  onlineStatusBatch(status: any) {
    if (this.messageId != null) {
      return;
    }
    let ids = this.listOfData.records.filter(function(item: any) {
      return item.Checked == true;
    }).map((ele: any) => {
      return ele.id;
    }).join(',');
    if (!ids) {
      return this.createMessage('warning', '请选择要上/下架的商品');
    }
    this.createBasicMessage();
    let json = {
      ids: ids,
      // 0 无效  1有效 2 下架（未上架）
      status: status
    };
    this.GoodsAllService.onlineStatusBatch(json).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.getList();
      // this.createMessage('success', status == 2 ? '批量下架成功' : '批量上架成功');
      this.createMessage('success', res.data);
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 下架
   * @returns
   */
  clickSwitch(id: any, status: any): void {
    if (this.messageId != null) {
      return;
    }

    this.createBasicMessage();
    this.GoodsAllService.onlineStatusBatch({ids: id, status: status}).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.getList();
      const msg: any = {1: '上架成功', 2: '下架成功'};
      this.createMessage('success', msg[`${status}`]);
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  // 商品分类 全选
  onSelectGoodsTypeAll(ev: any) {
    if (ev.includes('all')) {
      this.cacheData.goodsTypeIdList = [];
      this.GoodsTypeList?.forEach((element: any) => {
        const {id} = element;
        if (id) {
          this.cacheData.goodsTypeIdList.push(`${id}`);
        }
      });
    }
    this.queryForm.goodsTypeId = this.cacheData.goodsTypeIdList.join(',');
  }

  // select商品分类改变
  onChangeTree(event: any) {
    if (event) {
      this.queryForm.goodsTypeId = event.join(',');
    }
  }

  // 商品分类下拉数据处理
  addFieldArr(arr: any, key?: any, value: any = null, level: any = 0) {
    return arr.map((item: any) => {
      if (item.children && item.children.length > 0) {
        item.disabled = true;
        item.children = this.addFieldArr(item.children);
      }

      if (item.children && item.children.length <= 0) {
        item.isLeaf = true;
      }

      let obj: any = {
        ...item,
        key: item.id,
        title: item.name
      };
      return obj;
    });
  }

  // 商品品牌列表
  getBrandListData() {
    this.GoodsAllService.getBrandList().subscribe((res: any) => {
      this.cacheData.brandList = res.data || [];
    }, (error: any) => {
      this.cacheData.brandList = [];
    });
  }

  // 商品品牌change
  brandSelected(event: any) {
    this.queryForm.brandIds = event.join(',');
  }

  // 跳转京东页面
  jumpjdPage(jdId?: any) {
    window.open(`https://item.jd.com/${jdId}.html`, '_blank');
  }

  /**************************************** 水印添加 && 移除 START ****************************************/
  showModel(num :number) {
    this.identityOptions.map((item: any) => item.checked = false);
    this.modelForemParams.position = '';
    this.modelForemParams.type = '';

    let tempStr: string = num == 0 ? '添加' : '去除';
    this.checkedIds = this.listOfData.records.filter((item: any) => {
      return item.Checked == true;
    }).map((tag: any) => tag.id);
    if (this.checkedIds.length == 0) {
      this.message.warning(`请先选择需要 ${tempStr} 水印的商品!`);
      return;
    }
    this.modelType = num;
    this.isModelVisible = true;
  }

  handleOk(): void {
    if (!this.verifModel()) {
      return
    }
    let params: any = {
      idList: [],
      position: '',
      type: this.modelForemParams.type
    }
    let confirmStr: string = '';
    confirmStr = this.modelType == 0 ? `确定合成${this.checkedIds.length}个商品的水印图片?` : `确定去除${this.checkedIds.length}个商品的水印图片?`;
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: `<b style="color: red;">${confirmStr}</b>`,
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        // modelType: 0 新增，1 移除
        if (this.modelType == 0) {
          params.name = 'goods';
          params.file = this.modelForemParams.file;
          params.position = this.modelForemParams.position;
          params.idList = this.checkedIds.join(',');
          
          const formData: FormData = new FormData();
          for (let key in params) {
            formData.append(key, params[key]);
          }

          this.bathAddWatermark(formData);
        } else {
          delete params.name;
          delete params.imgList;
          delete params.file;
          delete params.position;
          delete params.idList;
          params.ids = this.checkedIds.join(',');

          this.bathRemoveWatermark(params);
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
  // Batch add
  async bathAddWatermark(params: any) {
    try {
      this.isConfirmLoading = true;
      const res: any = await this.GoodsAllService.addWatermarkData(params);
      this.isConfirmLoading = false;
      if (res.code == 0) {
        this.message.success(res.data || '添加成功');
        this.isModelVisible = false;
        this.getList();
      }
    } catch (error: any) {
      this.isConfirmLoading = false;
      this.message.error(error);
    }
  }
  // Batch remove
  async bathRemoveWatermark(params: any) {
    try {
      this.isConfirmLoading = true;
      const res: any = await this.GoodsAllService.removeWatermarkData(params);
      this.isConfirmLoading = false;
      if (res.code == 0) {
        this.message.success('去除成功');
        this.isModelVisible = false;
        this.getList();
      }
    } catch (error: any) {
      this.isConfirmLoading = false;
      this.message.error(error);
    }
  }

  handleCancel(): void {
    this.isModelVisible = false;
  }
  verifModel() {
    if (!this.modelForemParams.imgUrl && this.modelType == 0) {
      this.message.warning('请选择水印图片!');
      return false;
    } else if (!this.modelForemParams.type) {
      this.message.warning('请选择身份!');
      return false;
    } else if (!this.modelForemParams.position && this.modelType == 0) {
      this.message.warning('请选择水印位置!');
      return false;
    } else {
      return true;
    }
  }

  // 身份选择
  changeCheckbox(values: any) {
    let tempArr: any[] = values.map((item: any) => {
      if (item.checked) {
        return item.value;
      }
    }).filter((tag: any) => tag);

    if (tempArr.length == 2) {
      this.modelForemParams.type = '2';
    } else {
      this.modelForemParams.type = tempArr.join(',');
    }
  }

  // img upload
  onModalPreview({ file }: any): void {
    this.modelForemParams.file = file.originFileObj;
    this.getBase64(file!.originFileObj!, (img: string) => {
      this.uploadImgLoading = false;
      this.modelForemParams.imgUrl = img;
    });
  }
  getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }
  /**************************************** 水印添加 && 移除 END ****************************************/

  /**************************************** 货主 START ****************************************/
  async querySupplierList() {
    try {
      let params = {
        state: 1,
        page: this.cargoOwnerForms.page,
        pageSize: this.cargoOwnerForms.pageSize
      }
      this.isSelectLoading = true;
      const res: any = await this.GoodsAllService.querySupplierListData(params);
      this.isSelectLoading = false;
      if (res.code == 0 && res.data.records.length) {
        const { records, total }: any = res.data;
        if (this.cargoOwnerForms.page == 1) {
          this.cargoOwnerOptions = records || [];
        } else {
          this.cargoOwnerOptions = this.cargoOwnerOptions.concat(records);
        }
        this.cargoOwnerForms.total = total || 0;
      }
    } catch (error: any) {
      this.isSelectLoading = false;
      this.message.error(error);
      this.cargoOwnerOptions = [];
      this.cargoOwnerForms.total = 0;
    }
  }
  loadSupplierMore() {
    if (this.cargoOwnerForms.total != this.cargoOwnerOptions.length) {
      this.cargoOwnerForms.page += 1;
      this.querySupplierList();
    }
  }
  cargoOwnerChange(result: any) {
    this.queryForm.supplierIds = result.join(',');
  }
  /**************************************** 货主 END ****************************************/

  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在请求...', {nzDuration: 0}).messageId;
  }

  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }

  /**
   * 全局展示操作反馈信息
   * @param type 其他提示类型 success:成功 error:失败 warning:警告
   */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }
}
